<template>
  <el-row :gutter="20" style="margin-left: 5px;">
  <el-col :span="5">
    <el-input v-model="input" style="width: 300px;margin: 10px;" placeholder="请输入姓名或身份证号码"></el-input>
  </el-col>
  <el-col :span="6">
    <el-button style="margin: 10px;" type="primary" @click="selectUser()">查询</el-button>
  </el-col>

  <el-col :span="1" style="margin: 10px;"></el-col>

  <el-col :span="5" style="margin: 10px;">
    <el-select v-model="dept" @change="loadDocter();" placeholder="科室">
      <el-option v-for="item in depts" :key="item.id" :label="item.deptCode + item.deptName" :value="item.id" />
    </el-select>
  </el-col>

  <el-col :span="5" style="margin: 10px;">
    <el-select v-model="docter" @change="loadData(1)" placeholder="医生">
      <el-option v-for="item in docters" :key="item.id" :label="item.realName" :value="item.id" />
    </el-select>
  </el-col>
</el-row>

<el-row :gutter="20" style="margin-left: 5px;">
  <el-col :span="5">
    <!-- Left side: el-select -->
    <el-select style="margin: 10px;" v-model="level" @change="loadData(1)" placeholder="挂号级别">
      <el-option v-for="item in levels.records" :key="item.id" :label="item.registName" :value="item.id" />
    </el-select>
  </el-col>
  
  <el-col :span="13" style="margin: 10px;"></el-col>

  <el-col :span="5">
    <!-- Right side: el-button -->
    <el-button type="danger" @click="register()">现场挂号</el-button>
  </el-col>
</el-row>

  <el-table :data="users.records" ref="userTable" @selection-change="userSelectionChange" stripe
    style="width: 100%;margin-bottom: 50px;">
    <el-table-column type="selection" width="55">
    </el-table-column>
    <el-table-column prop="date" type="index" label="序号" width="180">
    </el-table-column>
    <el-table-column prop="realname" label="姓名" width="180">
    </el-table-column>
    <el-table-column prop="sex" label="性别">
    </el-table-column>
    <el-table-column prop="idnumber" label="身份证">
    </el-table-column>
    <el-table-column prop="birthdate" label="出生日期">
    </el-table-column>
    <el-table-column prop="phone" label="手机号">
    </el-table-column>
    <el-table-column prop="cardtypeName" label="卡类型">
    </el-table-column>
  </el-table>
  <el-table :data="scheduls.records" ref="docterTable" @selection-change="docterSelectionChange" stripe
    style="width: 100%">
    <el-table-column type="selection" width="55">
    </el-table-column>
    <el-table-column prop="realName" label="姓名" width="180">
    </el-table-column>
    <el-table-column prop="schedDate" label="日期" width="180">
    </el-table-column>
    <el-table-column prop="noon" label="午别">
    </el-table-column>
    <el-table-column prop="registName" label="号别">
    </el-table-column>
    <el-table-column prop="registFee" label="挂号费">
    </el-table-column>
    <el-table-column prop="ticket" label="余号">
    </el-table-column>
  </el-table>
</template>
<script setup>
import { ref, onMounted, watchEffect } from 'vue'
import { fetchData, postReq } from '../../utils/api'
import { ElMessageBox } from 'element-plus'

const depts = ref([])
const docters = ref([])
const levels = ref([])
const level = ref('')
const dept = ref('')
const docter = ref('')

const scheduls = ref({})
const users = ref({})
const input = ref('')

async function selectUser() {
  let url = `/medicalCard/page?keyword=${input.value}`
  const result = await fetchData(url, null);
  console.log(result)
  if (result.result) {
    users.value = result.data
    for (let i = 0; i < users.value.records.length; i++) {
      if (users.value.records[i].gender == 71) {
        users.value.records[i].sex = '男'
      } else if (users.value.records[i].gender == 72) {
        users.value.records[i].sex = '女'
      }
    }
  } else {
    if (result.errMsg == '未登录')
      router.push('/login')
  }
}
const registers = ref({})

function register() {
  console.log(calculateAge(userSelectino.birthdate))
  const now = new Date();

  const year = now.getFullYear();
  const month = ('0' + (now.getMonth() + 1)).slice(-2);
  const day = ('0' + now.getDate()).slice(-2);
  const hours = ('0' + now.getHours()).slice(-2);
  const minutes = ('0' + now.getMinutes()).slice(-2);
  const seconds = ('0' + now.getSeconds()).slice(-2);

  const formattedTime = year + month + day + hours + minutes + seconds;

  const selectedDocter = this.docters.find(item => item.id === docter.value);
  console.log(selectedDocter)
  console.log(doctersSelection)
  console.log(userSelectino)
  registers.value = {
    register: {
      age: calculateAge(userSelectino.birthdate),
      ageType: '岁',
      visitDate: doctersSelection.schedDate,
      noon: doctersSelection.noon,
      deptID: doctersSelection.deptID,
      userID: doctersSelection.userID,
      registLeID: doctersSelection.registlevelId,
      settleID: 185,
      isBook: 0,
      registTime: formattedTime,
      registerID: 10,
      visitState: 1,
      medicalCardId: userSelectino.id,
      channel: userSelectino.channel
    },
    registerVo: {
      realName: userSelectino.realname,
      gender: userSelectino.gender,
      phone: userSelectino.phone,
      birthDay: userSelectino.birthdate,
      age: calculateAge(userSelectino.birthdate),
      ageType: '岁',
      addr: userSelectino.addr,
      visitDate: doctersSelection.schedDate,
      noon: doctersSelection.noon,
      deptID: doctersSelection.deptID,
      deptName: doctersSelection.deptName,
      userID: doctersSelection.userID,
      DoctorName: doctersSelection.realName,
      registLeID: doctersSelection.registlevelId,
      registName: doctersSelection.registName,
      registFee: doctersSelection.registFee,
      settleID: 185,
      isBook: 0,
      registTime: formattedTime,
      registerID: 10,
      RegisterName: "hyq",
      visitState: 1,
      medicalCardId: userSelectino.cardNo,
      channel: userSelectino.channel,
      channelName: userSelectino.channelName
    },
    userVo: selectedDocter,
    scheduling: doctersSelection
  };
  console.log(registers.value)
  postReq("/register/add", registers.value).then(resp => {
    if (resp.data.result) {
      ElMessageBox.alert('挂号成功', '提示', {})
      loadData(1)
    } else {
      if (resp.result.errMsg == '未登录')
        router.push('/login')
    }

  })

}

async function loadDeptData() {
  let url = `/department/page?&count=200&pn=1`
  const result = await fetchData(url, null);
  if (result.result) {
    depts.value = result.data.records
  } else {
    if (result.errMsg == '未登录') {
      router.push('/login')
    }
  }
}

var userSelectino = ref({})
const userTable = ref();
function userSelectionChange(selection) {
  if (selection.length > 1) {
    let del_row = selection.shift();
    userTable.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
  }
  userSelectino = selection[0]
}

var doctersSelection = ref({})
const docterTable = ref();
function docterSelectionChange(selection) {
  if (selection.length > 1) {
    let del_row = selection.shift();
    docterTable.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
  }
  doctersSelection = selection[0]
}
async function loadDocter() {
  let url = `/user/page?userType=172?dept=${dept.value}`

  const result = await fetchData(url, null);
  if (result.result) {
    docters.value = result.data.records
  } else {
    if (result.errMsg == '未登录')
      router.push('/login')
  }
}
async function loadLevel() {
  let url = `/registlevel/page`

  const result = await fetchData(url, null);
  if (result.result) {
    levels.value = result.data
  } else {
    if (result.errMsg == '未登录')
      router.push('/login')
  }
}



//加载数据
async function loadData(pn) {

  let url = `/scheduling/page?pn=${pn}`

  if (dept != '')
    url += `&deptId=${dept.value}`
  if (docter != '')
    url += `&userId=${docter.value}`
  if (level != '')
    url += `&regLevel=${level.value}`

  const result = await fetchData(url, null);
  if (result.result) {
    scheduls.value = result.data
    for (let i = 0; i < scheduls.value.records.length; i++) {
      scheduls.value.records[i].ticket = scheduls.value.records[i].registQuota - scheduls.value.records[i].regNum
    }

  } else {
    if (result.errMsg == '未登录')
      router.push('/login')
  }
}
onMounted(async () => {
  selectUser()
  //loadData(1)
  loadLevel()
  loadDeptData()
});

function calculateAge(birthdate) {
  const today = new Date();
  const birthDate = new Date(birthdate);

  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();

  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }

  return age;
}
</script>

<style scoped ></style>